<?php
// 接口-销售统计
namespace interface\v1;

use verify;

class saleStatisticsClass extends index
{
	private const page    = 'saleOrder';
	private const table   = 'sale_order';
	private const tableMx = 'sale_order_detail';
	
	function index()
	{
		$this->code = 1;
		$months     = self::dateRange(date('Y-m-d', strtotime('-1 year')), date('Y-m-d'));
		$res        = [];
		foreach ($months as $m) {
			$twhere           = self::timeComparison($m, 'month', 'targetDate');
			$rwhere           = self::timeComparison($m, 'month', 'b.recordDate');
			$amountReceivable = find(array('table' => 'record', 'where' => " coid = '" . self::$coid . "' and classify = '销售发货' " . $twhere, 'sum' => "money"));
			$amountCollected  = (float)find(array('table' => "receipt_source as a join receipt as b on a.orderId = b.id", "single" => " coid = '" . self::$coid . "' and b.state = '已确认' and b.classify = 1 " . $rwhere, 'sum' => "money"));
			//核销单
			$amountCollected += (float)find(array('table' => "write_off_order_detail as a join write_off_order as b on a.orderId = b.id", "single" => " coid = '" . self::$coid . "' and b.state = '已确认' and b.type = '预收冲应收' " . $rwhere, 'sum' => "money"));
			$res[]           = [
				'amountReceivable' => round($amountReceivable / 10000, 2),
				'amountCollected'  => round($amountCollected / 10000, 2),
			];
		}
		$this->resp['data'] = [
			'title'     => ['应收金额', '收款金额'],
			'dateRange' => $months[0] . '~' . end($months),
			"data"      => $months,
			"series"    => [
				[
					'name'   => '应收金额',
					"type"   => 'line',
					"smooth" => 1,
					'data'   => array_column($res, 'amountReceivable'),
				],
				[
					'name'   => '收款金额',
					"type"   => 'line',
					"smooth" => 1,
					'data'   => array_column($res, 'amountCollected'),
				],
			],
		];
	}
	
	/**
	 * 按期交货率
	 *
	 * @return void
	 */
	function deliveryRate()
	{
		$this->code = 1;
		$months     = self::dateRange(date('Y-m-d', strtotime('-1 year')), date('Y-m-d'));
		$res        = [];
		foreach ($months as $m) {
			$res[] = [
				'onScheduleNum' => inventoryDefaultClass::deliveryRate('按期交货订单笔数', $m),
				'delayNum'      => inventoryDefaultClass::deliveryRate('延期交货订单笔数', $m),
			];
		}
		$this->resp['data'] = [
			'title'     => ['按期交货订单笔数', '延期交货订单笔数'],
			'dateRange' => $months[0] . '~' . end($months),
			"data"      => $months,
			"series"    => [
				[
					'name'   => '按期交货订单笔数',
					"type"   => 'bar',
					"smooth" => 1,
					'data'   => array_column($res, 'onScheduleNum'),
				],
				[
					'name'   => '延期交货订单笔数',
					"type"   => 'bar',
					"smooth" => 1,
					'data'   => array_column($res, 'delayNum'),
				],
			],
		];
	}
	
	/**
	 * 成本与利润
	 *
	 * @return void
	 */
	public function costProfit()
	{
		$this->code = 1;
		$months     = self::dateRange(date('Y-m-d', strtotime('-1 year')), date('Y-m-d'));
		$res        = [];
		foreach ($months as $m) {
			$res[] = [
				'cost'        => inventoryDefaultClass::costProfit('销售成本', $m),
				'grossProfit' => inventoryDefaultClass::costProfit('毛利润', $m),
			];
		}
		$this->resp['data'] = [
			'title'     => ['成本', '利润'],
			'dateRange' => $months[0] . '~' . end($months),
			"data"      => $months,
			"series"    => [
				[
					'name'   => '成本',
					"type"   => 'bar',
					"smooth" => 1,
					'data'   => array_column($res, 'cost'),
				],
				[
					'name'   => '利润',
					"type"   => 'bar',
					"smooth" => 1,
					'data'   => array_column($res, 'grossProfit'),
				],
			],
		];
	}
	
	
	/**
	 * 按客户
	 *
	 * @return void
	 */
	function kehu()
	{
		$where              = $this->post('date') ? self::timeComparison($this->post('date'), 'date', 'p.recordDate') : '';
		$sql                = " SELECT (@i:=@i+1) as no, s.companyName as name, any_value(IFNULL(SUM(money), 0)) as total FROM `" . self::table . "` as p,kehu as s,(SELECT @i:=0) as i WHERE p.khid = s.khid AND p.state = '已确认' AND p.coid = '" . self::$coid . "' {$where} GROUP BY p.khid ORDER BY total DESC; ";
		$resp               = self::sqlFind($sql);
		$this->code         = 1;
		$this->resp['data'] = array_merge([
			[
				'no'    => '排行',
				'name'  => '客户',
				'total' => '含税金额',
			],
		], $resp);
	}
	
	
	/**
	 * 按销售员
	 *
	 * @return void
	 */
	function staff()
	{
		$where              = $this->post('date') ? self::timeComparison($this->post('date'), 'date', 'p.recordDate') : '';
		$sql                = " SELECT (@i:=@i+1) as no, s.name, any_value(IFNULL(SUM(p.money), 0)) as total FROM `" . self::table . "` as p,staff as s,(SELECT @i:=0) as i WHERE p.manager = s.stid AND p.state = '已确认' AND p.coid = '" . self::$coid . "' {$where} GROUP BY p.manager ORDER BY total DESC; ";
		$resp               = self::sqlFind($sql);
		$this->code         = 1;
		$this->resp['data'] = array_merge([
			[
				'no'    => '排行',
				'name'  => '销售员',
				'total' => '含税金额',
			],
		], $resp);
	}
	
	/**
	 * 按商品
	 *
	 * @return void
	 */
	function material()
	{
		$where              = $this->post('date') ? self::timeComparison($this->post('date'), 'date', 'p.recordDate') : '';
		$sql                = "SELECT (@i:=@i+1) as no, m.name, any_value(IFNULL(sum(d.money*(1+d.rate)), 0)) as total FROM `" . self::table . "` as p, `" . self::tableMx . "` as d, `material` as m,(SELECT @i:=0) as i WHERE d.materialId = m.id AND p.id = d.orderId AND p.state = '已确认' AND p.coid = '" . self::$coid . "' {$where} GROUP BY materialId ORDER BY total DESC;";
		$resp               = self::sqlFind($sql);
		$this->code         = 1;
		$this->resp['data'] = array_merge([
			[
				'no'    => '排行',
				'name'  => '产品名称',
				'total' => '含税金额',
			],
		], $resp);
	}
	
	function orderToId()
	{
		$orderNo = $this->post('orderNo');
		if (self::isNull($orderNo)) {
			$this->resp['warn'] = '销售单号不能为空';
		} else {
			$info = query(self::table, " orderNo = '$orderNo'  ");
			if (empty($info['id'])) {
				$this->resp['warn'] = '未找到此单号的销售单';
			} else {
				$this->code         = 1;
				$this->resp['data'] = $info['id'];
			}
		}
	}
}




